package com.mj.postcode.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import com.mj.postcode.R;
import com.mj.postcode.config.Constants;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

/**
 * 数据库管理
Android开发 SQLite 通过.db文件导入已有数据库
http://www.android100.org/html/201303/27/2031.html
http://blog.csdn.net/lidhsr/article/details/7694956
http://my.oschina.net/helu/blog/142287
 * @author zhaominglei
 * @date 2015-11-10
 * 
 */
public class DBManager {
	private final int BUFFER_SIZE = 1024*10;
	
	public SQLiteDatabase openDatabase(Context context) {
		try {
			String filepath = Constants.FILE_PATH + "/" + Constants.DB_NAME;
			if (!new File(Constants.FILE_PATH).exists()) {
				new File(Constants.FILE_PATH).mkdir();
			}
			if (!new File(filepath).exists()) {
				InputStream is = context.getResources().openRawResource(R.raw.postcode);
				FileOutputStream fos = new FileOutputStream(filepath);
				byte[] buffer = new byte[BUFFER_SIZE];
				int count = 0;
				while((count = is.read(buffer)) > 0) {
					fos.write(buffer, 0, count);
				}
				fos.close();
				is.close();
			}
			SQLiteDatabase database = SQLiteDatabase.openOrCreateDatabase(filepath, null);
			return database;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
}
